<template>
  <div class="app-container">
    <div class="har-container">
      <div class="item" v-for="(item, index) in [1, 2, 3, 4]" :key="index">
        <template v-if="index === 0">
          <div class="tips">设备数量 (台)</div>
          <div class="num">{{ numberOfDevices }}</div>
        </template>
        <template v-if="index === 1">
          <div class="tips">在线设备 (台)</div>
          <div class="num">{{ numberOfDevices }}</div>
        </template>
        <template v-if="index === 2">
          <div class="tips">离线设备 (台)</div>
          <div class="num">{{ numberOfDevices }}</div>
        </template>
        <template v-if="index === 3">
          <div class="tips">未激活设备 (台)</div>
          <div class="num">{{ numberOfDevices }}</div>
        </template>
      </div>
    </div>
    <div class="main">
      <div class="filter-container g-bgc-fill-el-input">
        <div class="filter-left">
          <el-select v-model="listQuery.menufacturerId" placeholder="品牌" clearable @change="comHandleFilterSelectChange"
            style="width: 104px" class="filter-item">
            <el-option v-for="(item, index) in brandOptions" :key="'br' + index" :label="item.menufacturer"
              :value="item.id" />
          </el-select>
          <el-select v-model="listQuery.storage" placeholder="容量" clearable @change="comHandleFilterSelectChange"
            style="width: 104px" class="filter-item">
            <el-option v-for="(item, index) in storageOptions" :key="'st' + index" :label="item.label"
              :value="item.id" />
          </el-select>
          <!-- 设备没有软件版本 -->
          <!-- <el-select v-model="listQuery.importance" placeholder="软件版本" clearable @change="comHandleFilterSelectChange"
            style="width: 132px" class="filter-item">
            <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
          </el-select> -->
          <!-- 这一期前端弄不完 -->
          <!-- <el-select v-model="listQuery.p2pAddress" placeholder="所在地区" clearable @change="comHandleFilterSelectChange"
            class="filter-item" style="width: 132px">
            <el-option v-for="item in p2pAddressOptions" :key="item.key"
              :label="item.display_name + '(' + item.key + ')'" :value="item.key" />
          </el-select> -->
          <el-date-picker v-model="listQuery.date" type="daterange" @change="comHandleFilterDateChange"
            format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" style="width: 208px;" range-separator=""
            start-placeholder="开始时间" end-placeholder="结束时间">
          </el-date-picker>
          <el-select v-model="listQuery.activedState" placeholder="状态" clearable @change="comHandleFilterSelectChange"
            style="width: 104px" class="filter-item">
            <el-option v-for="item in activedStateOptions" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
          <np-input-search v-model="listQuery.deviceCode" placeholder="搜索序列号" style="width: 240px;"
            @all-search="comHandleFilterAllSearch" />
        </div>
        <div class="filter-right">
          <el-button type="warning" @click="handleImportDevices">导入设备</el-button>
          <el-button type="warning" @click="handleAddDevice">新增设备</el-button>
        </div>
      </div>

      <el-table class="g-el-table" :data="list" v-loading="listLoading">
        <el-table-column label="序列号" prop="deviceCode" width="300">
          <template slot-scope="{row}">
            <span>{{ row.deviceCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌" width="150px">
          <template slot-scope="{row}">
            <span>{{ row.deviceBrand }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备型号" min-width="150px">
          <template slot-scope="{row}">
            <span>{{ row.deviceModel }}</span>
          </template>
        </el-table-column>
        <el-table-column label="容量" width="110px">
          <template slot-scope="{row}">
            <span>{{ row.storage | storageFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="软件版本" width="80px">
          <template slot-scope="{row}">
            <span>{{ row.author }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所在地区" width="95">
          <template slot-scope="{row}">
            <span>{{ row.p2pAddress }}</span>
          </template>
        </el-table-column>
        <el-table-column label="激活时间" width="100">
          <template slot-scope="{row}">
            <span>{{ row.createdDate | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="{row}">
            {{ row.activedState | activedStateFilter }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="text" @click="handleEditDevice(row)">编辑</el-button>
            <el-button type="text" @click="handleViewDevice(row)">查看设备</el-button>
            <el-button type="text" @click="handleViewFamily(row)">查看家庭</el-button>
          </template>
        </el-table-column>
      </el-table>

      <np-pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
        @pagination="getList" />
    </div>

    <ImportDevicesDialog :visible.sync="dialogImportDevicesVisible" @importSuccess="importSuccess"
      :brand-options="brandOptions" />
    <EditDevicesDialog :visible.sync="dialogEditDevicesVisible" :info-row="editInfoRow" :brand-options="brandOptions"
      @editSuccessChange="editSuccessChange" />
  </div>
</template>

<script>
import { fetchList, getMenufacturers } from '@/api/equipment-management/list'
import { getMembersByDeviceCode } from '@/api/family-and-users-management/index'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import ImportDevicesDialog from "./components/ImportDevicesDialog.vue"
import EditDevicesDialog from "./components/EditDevicesDialog.vue"

const activedStateOptions = [
  // "激活状态,U:未激活,A:已激活"
  {
    label: '已激活',
    id: 'A',
  }, {
    label: '未激活',
    id: 'U',
  }
]

export default {
  name: 'ComplexTable',
  components: { ImportDevicesDialog, EditDevicesDialog },
  // directives: { waves },
  filters: {
    activedStateFilter(status) {
      let v = activedStateOptions.find(el => status === el.id)
      if (v) {
        return v.label
      }
      return '未激活'
    },
    storageFilter(val) {
      /**
       * 导入xls表等，没有单位默认就是 TB
       * 默认存储 GB 列表默认显示GB，如果大于 1Tb 单位就是 TB
       */
      try {
        let radix = 1024;
        let v = Number(val) || 0
        if (v >= radix) {
          // TB
          let a = Number(v / radix).toFixed(3)
          return parseFloat(a) + 'TB';
        }
        // GB
        return parseFloat(v) + 'GB';
      } catch (error) { }
      return ''
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      // 页面初始化调接口加载 Loading
      listLoading: true,
      // 页面筛选初始参数对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,

        menufacturerId: undefined,

        storage: undefined,
        startStorage: undefined,
        endStorage: undefined,

        importance: undefined,
        p2pAddress: undefined,
        activedState: undefined,
        deviceCode: undefined,

        date: undefined,
        startDate: undefined,
        endDate: undefined,

        importance: undefined,
        title: undefined,
        type: undefined,
      },
      brandOptions: [],
      // 容量单位为 TB
      storageOptions: [{
        id: [1, undefined],
        label: '1TB以下',
      }, {
        id: [1, 1],
        label: '1TB',
      }, {
        id: [1, 5],
        label: '1-5TB',
      }, {
        id: [undefined, 5],
        label: '5TB以上',
      }],
      p2pAddressOptions: [],
      activedStateOptions,

      importanceOptions: [],//没用后期要替换的

      //编辑参数
      editInfoRow: null,

      dialogImportDevicesVisible: false,
      dialogEditDevicesVisible: false,

      timerObj: {
        d1: null,
        t1: null,
      }
    }
  },
  computed: {
    numberOfDevices() {
      return this.total || ''
    }
  },
  created() {
    this.getList()
    getMenufacturers({ pageNum: 1, pageSize: 1000 }).then(res => {
      if (res.code === 200) {
        this.brandOptions = res.data.list || []
      }
    })
  },
  methods: {
    getList() {
      let params = { ...this.listQuery }
      delete params.date
      let st = params.storage
      if (st) {
        let radix = 1024;
        if (st[0]) {
          params.startStorage = st[0] * radix
        }
        if (st[1]) {
          params.endStorage = st[1] * radix
        }
      }
      delete params.storage

      this.listLoading = true
      fetchList(params).then(res => {
        if (res.code === 200) {
          this.list = res.data.list
          this.total = res.data.total
        }

        // Just to simulate the time of the request
        this.listLoading = false
      }).catch((error) => {
        this.listLoading = false
      })
    },
    comHandleFilterAllSearch(e, type) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterSelectChange(e) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterDateChange(e) {
      this.listQuery.pageNum = 1
      this.listQuery.startDate = e ? e[0] : ''
      this.listQuery.endDate = e ? e[1] : ''
      this.getList()
    },
    handleImportDevices() {
      this.dialogImportDevicesVisible = true
    },
    importSuccess() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    editSuccessChange(e) {
      this.editInfoRow = null;
      this.getList()
    },
    handleAddDevice() {
      this.editInfoRow = null
      this.dialogEditDevicesVisible = true
    },
    handleEditDevice(row) {
      this.editInfoRow = row
      this.dialogEditDevicesVisible = true
    },
    handleViewDevice(row) {
      this.$router.push(`/equipment/view-device?deviceCode=${row.deviceCode}`)
    },
    handleViewFamily(row) {
      // console.log(row);
      //先判断有没有创建家庭圈,通过这个接口判断, getMembersByDeviceCode 有数据返回就说明创建了，没有数据就代表没有创建
      this.DebounceOrThrottle(() => {
        getMembersByDeviceCode({ deviceCode: row.deviceCode }).then(res => {
          if (res.data?.length) {
            this.$router.push({
              path: `/family-and-users/family/family-information`,
              query: {
                groupId: row.groupId || '',
                deviceCode: row.deviceCode || '',
              }
            })
            return
          }
          this.$message.error('还没有创建家庭圈')
        }).catch(err => {
          this.$message.error('网络连接失败，服务失败！')
        })
      }, 600, 'throttle')
    },
    DebounceOrThrottle(callback, limIs, is_debounce = "debounce") {
      limIs = Number(limIs) || limIs == 0 ? limIs : 400;
      if (is_debounce == "throttle") {
        if (!this.timerObj.t1) {
          this.timerObj.t1 = setTimeout(() => {
            callback();
            this.timerObj.t1 = null;
          }, limIs);
        }
      } else {
        if (this.timerObj.d1 != null) clearTimeout(this.timerObj.d1);
        this.timerObj.d1 = setTimeout(callback, limIs);
      }
    },
  }
}
</script>
<style scoped lang="scss">
.app-container {
  height: 100%;
  overflow: auto;
}

.har-container {
  display: grid;
  grid-gap: 20px 20px;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  padding-bottom: 20px;

  .item {
    background-color: #fff;
    border-radius: 16px;
    padding: 20px 24px;

    .tips {
      font-size: 14px;
      line-height: 18px;
      color: #8B8B8B;
    }

    .num {
      font-size: 28px;
      font-weight: 500;
      line-height: 36px;
      color: #15181D;
    }
  }
}

.main {
  background-color: #fff;
  border-radius: 16px;
  padding: 20px 20px 28px;
}
</style>